<template>
  <div class="factories-container">
    <h2>工厂列表</h2>
    <div class="factory-grid">
      <FactoryCard
          v-for="factory in factories"
          :key="factory.id"
          :factory="factory"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import FactoryCard from './components/FactoryCard.vue';
import { useSSE } from '@/utils/sse';
// 导入公共类型
import type { Factory } from '@/types/factory';



const factories = ref<Factory[]>([]);
let sseClient: any = null;

onMounted(() => {
  // 拼接代理前缀与接口路径
  const sseUrl = `${import.meta.env.VITE_PROXY_PREFIX}/view/factoryList`;
  // 建立SSE连接获取实时数据
  sseClient = useSSE(sseUrl, (event) => {
    const data = JSON.parse(event.data);
    if (data.type === 'error') {
      console.error('连接错误:', data.content); // 输出错误消息
      sseClient.close(); // 主动关闭连接
    } else {
      console.log('普通数据:', data.content); // 处理正常数据
      factories.value = data.content;
    }

  });
});

onUnmounted(() => {
  // 关闭SSE连接
  sseClient?.close();
});
</script>
